package com.andaily.service.impl;

import com.andaily.domain.developer.Backlog;
import com.andaily.domain.developer.BacklogRepository;
import com.andaily.domain.developer.operation.BacklogFormPersister;
import com.andaily.domain.dto.developer.BacklogDto;
import com.andaily.domain.dto.developer.BacklogFormDto;
import com.andaily.domain.dto.developer.BacklogOverviewDto;
import com.andaily.domain.shared.paginated.PaginatedLoader;
import com.andaily.service.BacklogService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * Date: 13-9-7
 *
 * @author Shengzhao Li
 */
public class BacklogServiceImpl implements BacklogService {


    @Autowired
    private BacklogRepository backlogRepository;

    @Override
    public BacklogFormDto loadBacklogFormDto(String guid) {
        BacklogFormDto backlogFormDto = new BacklogFormDto(guid);
        if (!backlogFormDto.isNewly()) {
            Backlog backlog = backlogRepository.findByGuid(guid);
            backlogFormDto = new BacklogFormDto(backlog);
        }
        return backlogFormDto;
    }

    @Override
    public String persistBacklogFormDto(BacklogFormDto backlogFormDto) {
        BacklogFormPersister backlogFormPersister = new BacklogFormPersister(backlogFormDto);
        return backlogFormPersister.persist();
    }

    @Override
    public BacklogOverviewDto loadBacklogOverviewDto(BacklogOverviewDto backlogOverviewDto) {
        final Map<String, Object> map = backlogOverviewDto.queryMap();
        return backlogOverviewDto.load(new PaginatedLoader<BacklogDto>() {
            @Override
            public List<BacklogDto> loadList() {
                List<Backlog> backlogs = backlogRepository.findOverviewBacklogs(map);
                return BacklogDto.toDtos(backlogs);
            }

            @Override
            public int loadTotalSize() {
                return backlogRepository.totalOverviewBacklogs(map);
            }
        });
    }

    @Override
    public void archiveBacklog(String guid) {
        Backlog backlog = backlogRepository.findByGuid(guid);
        backlog.archive().saveOrUpdate();
    }
}
